﻿using Domain;
using SQLite.Reps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Accessors
{
    public class CircleAccessor
    {
        public CircleRep _circleRepo;
        public WordRep _wordRepo;

        public CircleAccessor(CircleRep dictionaryRepo, WordRep wordRepo)
        {
            _wordRepo = wordRepo;
            _circleRepo = dictionaryRepo;
        }

        public async Task<IEnumerable<CircleLookup>> GetCirclesLookups()
        {
            var dbRes = await _circleRepo.GetAll();
            var res = dbRes.Select(x => new CircleLookup(x.Id, x.Name));
            return res;
        }

        public async Task<Circle> GetCircle(Guid id)
        {
            var dbCirleRes = await _circleRepo.GetByIdAsync(id);
            var dbWordsRes = await _wordRepo.GetByDictionaryId(id);
            var res = new Circle(dbCirleRes.Id, dbCirleRes.Name, dbWordsRes.Select(x => new Word(x.Id) { EnglishWord = x.EnglishWord, RussianWord = x.RussianWord, Examples = x.Examples, KnownCounter = x.KnownCounter, LastKnownDate = x.LastKnownDate }).ToList());
            return res;
        }

        public async Task InsertCircle(Circle circle)
        {
            var toInsert = new SQLite.DbEntities.CircleDbEntity() { Id = circle.Id, Name = circle.Name };
            await _circleRepo.InsertAsync(toInsert);

            foreach (var word in circle.ToList())
            {
                await InsertWord(word, circle.Id);
            }
        }

        public async Task InsertWord(Word word, Guid circleId)
        {
            var dbWord = ToDbEntity(word, circleId);
            await _wordRepo.InsertAsync(dbWord);
        }

        private static SQLite.DbEntities.WordDbEntity ToDbEntity(Word word, Guid circleId)
        {
            var dbWord = new SQLite.DbEntities.WordDbEntity() { FK_CircleId = circleId, Id = word.Id, RussianWord = word.RussianWord, EnglishWord = word.EnglishWord, Examples = word.Examples, KnownCounter = word.KnownCounter, LastKnownDate = word.LastKnownDate };
            return dbWord;
        }

        public async Task UpdateWord(Guid circleId, Word w)
        {
            var dbWord = ToDbEntity(w, circleId);
            await _wordRepo.UpdateAsync(dbWord);
        }
    }
}
